const path = require("path");
const Package = require("@cheng-cli-dev/package");
const log = require("@cheng-cli-dev/log");

const SETTINGS = {
  init: "@imooc-cli/init",
  // publish: "@imooc-cli/publish",
};

const CACHE_DIR = "dependencies";

/**
 * 采用两种方式找到init模块
 * 1.cheng-cli-dev init --targetPath E:\user_project\cli\cheng-cli-dev\commands\init --debug test\-project --force
 * 通过--targetPath传入绝对路径的init模块
 * 2.找到缓存路径加载init模块
 */
async function exec() {
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;
  let storePath = ""; // 缓存路径;
  let package = null;

  log.verbose("targetPath", targetPath);
  log.verbose("homePath", homePath);

  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  const packageName = SETTINGS[cmdName];
  const packageVersion = "latest";
  let modulePath = "";
  //1.获取init模块的路径 第一种方式用户通过命令传入绝对路径 第二种在缓存目录找，如果没找到npminstall
  //2.获取模块的package.json
  //3.获取模块的main文件
  if (!targetPath) {
    targetPath = path.resolve(homePath, CACHE_DIR);
    storePath = path.resolve(targetPath, "node_modules");

    log.verbose("targetPath", targetPath);
    log.verbose("storePath", storePath);
    let package = new Package({
      targetPath,
      storePath,
      packageName,
      packageVersion,
    });
    if (package.exists()) {
      await package.update();
    } else {
      await package.install();
    }
    modulePath = package.getRootFilePath();
  } else {
    package = new Package({
      targetPath,
      packageName,
      packageVersion,
    });
    modulePath = package.getRootFilePath();
  }
  if (modulePath) {
    require(modulePath).apply(null, arguments);
  }
}

module.exports = exec;
